package com.linwen.javase.thread;

/**
 * @author : linwen
 * @date : 下午8:02 2021/1/10
 * 继承Thread类 用同步代码块方式
 */
public class 线程锁2 {
    public static void main(String[] args) {
        Window2 window1 = new Window2();
        Window2 window2 = new Window2();
        Window2 window3 = new Window2();

        window1.setName("窗口1");
        window2.setName("窗口2");
        window3.setName("窗口3");
        window1.start();
        window2.start();
        window3.start();
    }
}
class Window2 extends Thread{
    //继承中定义需要定义为static的
    private static int ticket = 100;

    @Override
    public void run() {
        //注意！！不能在while前synchronized，否则就成了单线程循环卖完所以票
        while (true){
            //前面非同步的代码在之前做了
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //开发中用当前类对象
            synchronized (Window2.class){
                if(ticket>0) {

                    System.out.println(Thread.currentThread().getName() + "==" + ticket);
                    ticket--;
                }else{
                    break;
                }
            }
        }

    }
}
